package com.dodayum.service;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class MinioService {

    @Value("${minio.bucket-name}")
    private String BUCKET_NAME;

    @Resource
    private MinioClient minioClient;

    public String save(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String ext = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + ext;
        log.info("报错的文件：{}",fileName);
        try(InputStream inputStream = file.getInputStream()){
            PutObjectArgs build = PutObjectArgs.builder()
                    .bucket(this.BUCKET_NAME).object(fileName).stream(inputStream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(build);

        }
        return fileName;
    }

    public byte[] get(String fileName) throws Exception {
        InputStream  stream = minioClient.getObject(GetObjectArgs.builder().bucket(this.BUCKET_NAME).object(fileName).build());
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        while ((bytesRead = stream.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        return output.toByteArray();
    }

    public void delete(String fileName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(this.BUCKET_NAME).object(fileName).build());
    }
}
